package com.hzeport.bgs22emduty.inbound.api;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzeport.bgs22emduty.config.ProfileNotEqual;
import com.hzeport.bgs22emduty.config.interptor.ServletAttributes;
//import com.hzeport.bgs22emduty.config.login.LoginCompoent;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.entity.SystemModule;
import com.hzeport.bgs22emduty.outbound.SystemModuleRepository;
import com.hzeport.bgs22emduty.service.SystemModuleService;
import com.hzeport.bgs22emduty.vo.SystemModule.SystemModuleVO;
import com.hzeport.bgs22emduty.auth.adapter.UserService;
import com.hzeport.bgs22emduty.auth.dto.Function;
import com.hzeport.bgs22emduty.auth.dto.Role;
import com.hzeport.bgs22emduty.auth.dto.User;
import com.hzeport.bgs22emduty.auth.h4a.constant.H4AEnum;
import com.hzeport.bgs22emduty.auth.h4a.dto.H4aUser;
import com.hzeport.bgs22emduty.auth.porperty.SystemProperties;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zwj
 * @desc H4Aq权限菜单
 * @date 2021-11-11 17:00
 */
@Slf4j
@RestController
@RequestMapping("/H4AUser")
@Api(value = "H4AUser", tags = "H4A用户接口")
@AllArgsConstructor
@ProfileNotEqual("bgs22emduty")
public class H4AUserController {
    public final UserService userService;

    public final SystemProperties systemProperties;

    public final LoginCompoentService loginCompoentService;

    @Resource
    private SystemModuleService systemModuleService;
    @Autowired
    private SystemModuleRepository systemModuleRepository;
    /**
     * @param request
     * @return
     * @Authentication(roles = "FORUM_ADMIN") 权限校验
     */
//    @Authentication(roles = "MANAGER")
    @ApiOperation(value = "获取用户信息")
//    @ApiImplicitParam(name = "ticket", value = "token", required = true, dataType = "string", paramType = "header")
    @GetMapping("/userInfo")
    public BaseResult<UserInfoDetailVO> getUserInfo(HttpServletRequest request) {
//        String ticket= ServletAttributes.getRequest().getHeader(H4AEnum.HEAD_TICKET.getValue());
////        User user=userService.getUsers(ticket);
//        H4aUser h4aUser = (H4aUser) request.getSession().getAttribute(H4AEnum.HEAD_TICKET.getValue() );
//        log.info("进入获取用户信息"+h4aUser);
        UserInfoDetailVO user = loginCompoentService.getUserInfo();
        if(user.getRole().contains("SCHEDULE_MGR")){
            user.setIsAuth("1");
        }else {
            user.setIsAuth("0");
        }
//        User user= JSONObject.parseObject("{\n" +
//                "\t\"hrcode\": \"2905930\",\n" +
//                "\t\"name\": \"周某某\",\n" +
//                "\t\"customscode\": \"2900\",\n" +
//                "\t\"rankName\": \"副主任科员\",\n" +
//                "\t\"fullPath\": \"海关总署\\\\杭州海关\\\\办公室\\\\秘书科\\\\周某某\",\n" +
//                "\t\"parentId\": \"1ff2ab03-a575-47a7-81e7-5a097a4f17f9\",\n" +
//                "\t\"organization\": \"办公室,秘书科\",\n" +
//                "\t\"sideLine\": true,\n" +
//                "\t\"entract\": null\n" +
//                "}",User.class);
        return BaseResult.ok(user);
    }

//    @Authentication(roles = "MANAGER")
    @ApiOperation(value = "获取用户角色")
//    @ApiImplicitParam(name = "ticket", value = "token", required = true, dataType = "string", paramType = "header")
    @GetMapping("/getRoles")
    public BaseResult<List<Role>> getRoles(HttpServletRequest request) {
        log.info("进入获取用户角色");
        String ticket = request.getHeader(H4AEnum.HEAD_TICKET.getValue());
        List<Role> roles = userService.getRoles(ticket);
//        Role role=new Role();
//        role.setCode_name("MANAGER");
////        role.setCode_name("CJCONTACT");
//        List<Role> roles= Arrays.asList(role);
        return BaseResult.ok(roles);
    }

//    @Authentication(roles = "MANAGER")
    @ApiOperation(value = "获取用户菜单")
//    @ApiImplicitParam(name = "ticket", value = "token", required = true, dataType = "string", paramType = "header")
    @GetMapping("/menuInfo")
    public BaseResult<List<SystemModuleVO>> getMenuInfo(HttpServletRequest request) {
        log.info("进入获取用户菜单");
        String ticket = request.getHeader(H4AEnum.HEAD_TICKET.getValue());
        log.info("进入获取用户菜单"+ticket);
        final List<Function> functions = userService.getFunctions(ticket);
        log.info("获取到的功能点："+ JSON.toJSONString(functions));
         List<String> functionCodes = functions.stream().map(Function::getCode_name)
                .collect(Collectors.toList());
//
//        functionCodes.add("11000");
        //菜单树集合
             UserInfoDetailVO userInfoDetailVO=loginCompoentService.getUserInfo();
        List<SystemModuleVO> systemModuleVOList = new ArrayList<>();
//        全部菜单
        List<SystemModule> List=systemModuleRepository.list();
        List<Role> roles= userService.getRoles(ticket);
        log.info("获取到的用户角色:"+JSON.toJSONString(roles));
//        if (userInfoDetailVO.getRole()!=null&&userInfoDetailVO.getRole().contains("ZGGLY")) {
//        if(CollectionUtil.isNotEmpty(roles)&&roles.contains("ZGGLY")){
//            List  = systemModuleRepository.list(new LambdaQueryWrapper<SystemModule>()
//            .in(SystemModule::getWNamespace, Arrays.asList("1","3")));
//        }else {
//            List  = systemModuleRepository.list(new LambdaQueryWrapper<SystemModule>()
//                    .in(SystemModule::getWNamespace, Arrays.asList("2","3")));
//        }

        log.info("过滤功能点前的菜单:"+JSON.toJSONString(List));
        //菜单树为空
        //在全部菜单中找到每个人对应功能点菜单
        List<SystemModule> moduleList=new ArrayList<>();
//            for (String functionCode : functionCodes) {
        moduleList=List.stream().filter(i ->i!=null&&i.getFauthorityid()!=null&&functionCodes.contains(i.getFauthorityid())).collect(Collectors.toList());
//            }
        log.info("所有需要显示的菜单:"+JSON.toJSONString(moduleList));
        //菜单排序
        List<SystemModule> moduleLists=moduleList.stream().filter(i->1!=i.getMLevel()).sorted(Comparator.comparing(SystemModule::getForderindex)).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(moduleLists)){
            List<String> parentIds=moduleLists.stream().map(i->i.getFsuperid()+"").distinct().collect(Collectors.toList());
            List<SystemModule> parents=systemModuleRepository.list(
                    new LambdaQueryWrapper<SystemModule>()
                    .in(SystemModule::getId,parentIds)
                    .orderByAsc(SystemModule::getForderindex)
            );
            //        找到一级菜单
            for (SystemModule systemModule : parents) {
                if(systemModule.getMLevel()==1){
                    //根据一级菜单找到二级
                    List<SystemModuleVO> Children=new ArrayList<>();  //二级菜单集合
                    SystemModuleVO systemModuleVO = new SystemModuleVO();//菜单树对象
                    systemModuleVO.setId(systemModule.getId());
                    systemModuleVO.setLabel(systemModule.getFmainalias());
                    systemModuleVO.setForderindex(systemModule.getForderindex());
                    systemModuleVO.setPath(systemModule.getWPath());
                    getChild(systemModuleVO,Children,List,moduleList);//递归找到二级菜单
                    //二级菜单排序
                    List<SystemModuleVO> Childrens=Children.stream().sorted(Comparator.comparing(SystemModuleVO::getForderindex)).collect(Collectors.toList());
                    systemModuleVO.setChildren(Childrens);
                    //添加到集合
                    systemModuleVOList.add(systemModuleVO);
                }
//                if(systemModule.getMLevel()==1.5) {
//                    //根据一级菜单找到二级
//                    List<SystemModuleVO> Children = new ArrayList<>();  //二级菜单集合
//                    getChild(systemModule, Children, List, moduleList);//递归找到二级菜单
//                    //二级菜单排序
//                    List<SystemModuleVO> Childrens = Children.stream().sorted(Comparator.comparing(SystemModuleVO::getForderindex)).collect(Collectors.toList());
//                    SystemModuleVO systemModuleVO = new SystemModuleVO();//菜单树对象
//                    systemModuleVO.setId(systemModule.getId());
//                    systemModuleVO.setLabel(systemModule.getFmainalias());
//                    systemModuleVO.setPath(systemModule.getWPath());
//                    systemModuleVO.setChildren(Childrens);
//                    //添加到集合
//                    systemModuleVOList.add(systemModuleVO);
//                }

        }
        }
        systemModuleVOList=systemModuleVOList.stream().sorted(Comparator.comparing(SystemModuleVO::getForderindex)).collect(Collectors.toList());
        return BaseResult.ok(systemModuleVOList);
    }
    private void  getChild(SystemModuleVO systemModule, List<SystemModuleVO> Children , List<SystemModule> moduleList,List<SystemModule> needList){
        List<SystemModule> myChildren=moduleList.stream().filter(i->i.getFsuperid()!=null&&i.getFsuperid().toString().equals(systemModule.getId())).collect(Collectors.toList());
        List<SystemModuleVO> myChildrenVO=new ArrayList<>();
        for (SystemModule myChild : myChildren) {
            if (!needList.contains(myChild)){
                continue;
            }
            SystemModuleVO systemModuleVO = new SystemModuleVO();
            systemModuleVO.setId(myChild.getId());
            systemModuleVO.setLabel(myChild.getFmainalias());
            systemModuleVO.setPath(myChild.getWPath());
            systemModuleVO.setForderindex(myChild.getForderindex());
            myChildrenVO.add(systemModuleVO);
        }
        if (!CollectionUtils.isEmpty(myChildren)){
            Children.addAll(myChildrenVO);
            for (SystemModuleVO child:myChildrenVO){
                List<SystemModuleVO> nextLevelChild=new ArrayList<>();
                getChild(child,nextLevelChild,moduleList,needList);
                child.setChildren(nextLevelChild);
            }
        }else {
            return ;
        }
    }
    @ApiOperation(value = "全部菜单", notes = "菜单")
    @GetMapping("/systemModule")
    public BaseResult systemModule()  {
        return BaseResult.ok(loginCompoentService.systemModule());
    }


    @ApiOperation(value = "获取关区列表", notes = "获取关区列表")
    @GetMapping("/getCustomCodes")
    public BaseResult getCustomCodes ()  {
        return BaseResult.ok(loginCompoentService.getCustomCodes());
    }


    @ApiOperation(value = "选择关区", notes = "获取关区列表")
    @PostMapping("/setCustom")
    public BaseResult getCustomCodes ( @RequestParam("customCode")String customCode )  {
        return BaseResult.ok(loginCompoentService.setCustom(customCode));
    }

}
